package com.killer.handler;

import com.killer.pojo.User;
import com.killer.rpc.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * 自定义rpc客户端处理类
 */
public class RpcClientHandler extends ChannelInboundHandlerAdapter implements Callable{


    private ChannelHandlerContext ctx;

    /**
     * Rpc请求对象
     */
    private RpcRequest rpcRequest;

    /**
     * 返回的结果
     */
    private String result;


    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx=ctx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将服务端读取到的值赋值给result
        result=msg.toString();
    }

    public Object call() throws Exception {
        //将该rpc请求发送给服务端
        ctx.writeAndFlush(rpcRequest);
        int i=0;
        while (result == null) {
            //同时必须设定超时机制
            if (i >= 10) {
                break;
            }
            //不断读取，知道result不为null为止
            Thread.sleep(1000);
            i++;
        }
        return result;
    }
}
